package com.konne.nightmare.FastPublicOpinion.utils;

import android.app.ActivityManager;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class StringUtils {

    /***
     * 判断时间是否在时间段内
     */
    public static boolean isBelong(String time1, String time2) {

        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
        Date now = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            now = df.parse(df.format(new Date()));
            beginTime = df.parse(time1);
            endTime = df.parse(time2);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Calendar date = Calendar.getInstance();
        date.setTime(now);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }


    //计算时间
    public static long TimeDifference(String time2) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /* 当前系统时间*/
        Date date = new Date(System.currentTimeMillis());
        String time1 = simpleDateFormat.format(date);

        /*计算时间差*/
        Date begin = null;
        Date end = null;
        try {
            begin = simpleDateFormat.parse(time1);
            end = simpleDateFormat.parse(time2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = end.getTime() - begin.getTime();
        /*计算天数*/
        long days = diff / (1000 * 60 * 60 * 24);
        /*计算小时*/
        long hours = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        /*计算分钟*/
        long minutes = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60);
        /*计算秒*/
        long seconds = (diff % (1000 * 60)) / 1000;
        /*  输出
        System.out.println("保鲜的日期时间差：" + days + "天" + hours + "小时" + minutes + "分" + seconds + "秒");*/
        String daojishi = days + "-" + hours + "-" + minutes + "-" + seconds;

        return minutes;
    }


    //计算时间---多长时间以前
    public static String TimeDcomputing(String time2) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /* 当前系统时间*/
        Date date = new Date(System.currentTimeMillis());
        String time1 = simpleDateFormat.format(date);

        /*计算时间差*/
        Date begin = null;
        Date end = null;
        try {
            begin = simpleDateFormat.parse(time1);
            end = simpleDateFormat.parse(time2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = begin.getTime() - end.getTime();
        /*计算天数*/
        long days = diff / (1000 * 60 * 60 * 24);
        /*计算小时*/
        long hours = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        /*计算分钟*/
        long minutes = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60);
        /*计算秒*/
        long seconds = (diff % (1000 * 60)) / 1000;

        if (days > 0) {
            return days + "天前";
        }
        if (hours > 0) {
            return hours + "小时前";
        }
        if (minutes > 0) {
            return minutes + "分钟前";
        }
        if (seconds > 0) {
            return seconds + "秒前";
        }
        return null;
    }

    /**
     * 隐藏控件
     *
     * @param views
     */
    public static void gone(View... views) {
        if (null != views && views.length > 0) {
            for (View view : views) {
                if (null != view) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 设置银行卡
     *
     * @param bankNo
     * @return
     */
    public static String getBank(String bankNo) {
        char[] bankNoArray = bankNo.toCharArray();
        String bankNoString = "";
        for (int i = 0; i < bankNoArray.length; i++) {
            if (i % 4 == 0 && i > 0) {
                bankNoString += " ";
            }
            bankNoString += bankNoArray[i];
        }
        return bankNoString;
    }

    /**
     * 显示控件
     *
     * @param views
     */

    public static void visible(View... views) {
        if (null != views && views.length > 0) {
            for (View view : views) {
                if (null != view) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }
    }


    //设置手机号中间四位为****
    public static String getPhone(String mobile) {
        if (mobile != null) {
            return mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
        }
        return null;
    }


    /**
     * 时间戳转换为 年月日时分秒
     *
     * @param s
     * @return
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    public static String dealDateFormat(String oldDateStr) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS");  //yyyy-MM-dd'T'HH:mm:ss
        Date date = df.parse(oldDateStr);
        date.setHours(date.getHours()+8); //  一个 T 是 8 小时，虽然不知道为什么等于 8 ，但可以测试出来
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        return df2.format(date);
    }

    public static boolean isPhoneNumberValids(String phoneNumber) {
        boolean isValid = false;
        if (phoneNumber.length() == 12) {
            String expression = "0\\d{2,3}[1-9]\\d{6,7}";
            CharSequence inputStr = phoneNumber;

            Pattern pattern = Pattern.compile(expression);

            Matcher matcher = pattern.matcher(inputStr);

            if (matcher.matches()) {
                isValid = true;
            }

        } else {
            String expression = "((^(13|14|15|16|17|18|19)[0-9]{9}$)|(^0[1-9]{1}\\d{1}-?\\d{8}$)|(^0[0-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
            CharSequence inputStr = phoneNumber;

            Pattern pattern = Pattern.compile(expression);

            Matcher matcher = pattern.matcher(inputStr);

            if (matcher.matches()) {
                isValid = true;
            }

        }

        return isValid;

    }

    /**
     * 正则校验手机号码
     */
    public static boolean isTelPhoneNumber(String value) {
        if (value != null && value.length() == 11) {
            Pattern pattern = Pattern.compile("^1\\d{10}$");
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        }
        return false;
    }

    /**
     * 判断用户手机是否联网
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 实现文本复制功能
     *
     * @param content
     */
    public static void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    // 过滤特殊字符
    public static String StringFilterOne(String str) throws PatternSyntaxException {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;

    }

    /***
     * 判断应用是否运行
     *
     * @param context
     * @param action
     * @return
     */
    public static boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return resolveInfo.size() > 0;
    }

    /***
     * 获取包名
     *
     * @param context
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /***
     * 判断微信是否安装
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断qq是否安装
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionCode + "";
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "1";
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName + "";
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "v1.0.0";
    }


    /**
     * 验证密码是否包含字母
     *
     * @param password
     * @return
     */
    public static boolean isHasLetter(String password) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            list.add((char) (65 + i) + "");
        }
        for (int i = 0; i < 26; i++) {
            String letter = (char) (65 + i) + "";
            list.add(letter.toLowerCase());
        }
        for (int i = 0; i < password.length(); i++) {
            String passwordValue = password.charAt(i) + "";
            for (int j = 0; j < list.size(); j++) {
                if (passwordValue.equals(list.get(j))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 验证密码是否包含数字
     *
     * @param password
     * @return
     */
    public static boolean isHasNumber(String password) {
        List<String> list = new ArrayList<>();
        list.add("0");
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        list.add("7");
        list.add("8");
        list.add("9");
        for (int i = 0; i < password.length(); i++) {
            String passwordValue = password.charAt(i) + "";
            for (int j = 0; j < list.size(); j++) {
                if (passwordValue.equals(list.get(j))) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isEmpty(Object obj) {
        boolean b = null == obj || "".equals(obj);
        return b;
    }

    public static String stringToDate(String lo) {
        long time = Long.parseLong(lo);
        Calendar c = Calendar.getInstance();//
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(time);
    }

    /**
     * 计算返回传入时间加上@param minutes 后的时间
     *
     * @param lo
     * @param minutes
     * @return
     */
    public static String stringToHHmm(String lo, int minutes) {
        long time = Long.parseLong(lo) + (minutes * 60 * 1000);
        Calendar c = Calendar.getInstance();//
        SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
        return sd.format(time);
    }
}
